package com.example.aiserver.service.impl;

import com.example.aiserver.entity.User;
import com.example.aiserver.repository.UserRepository;
import com.example.aiserver.service.UserService;
import com.example.aiserver.util.PasswordUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {

    private final UserRepository userRepository;

    @Override
    public String loginWithDetails(String username, String password) {
        Optional<User> optionalUser = userRepository.findByUsername(username);
        if (!optionalUser.isPresent()) {
            return "USER_NOT_FOUND";
        }
        User user = optionalUser.get();
        if (!user.getPassword().equals(PasswordUtils.encrypt(password))) {
            return "PASSWORD_INCORRECT";
        }
        return "LOGIN_SUCCESS";
    }

    @Override
    public String registerWithDetails(String username, String password) {
        if (userRepository.findByUsername(username).isPresent()) {
            return "USER_EXISTS";
        }
        User user = new User();
        user.setUsername(username);
        user.setPassword(PasswordUtils.encrypt(password));
        userRepository.save(user);
        return "REGISTER_SUCCESS";
    }
}
